package com.briup.day19;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class CallableTest {
    public static void main(String[] args) throws Exception {
        long start = System.currentTimeMillis();
        // 调用以下三个方法，生成订单信息
       /* String goodsInfo = getGoodsInfo();
        String userInfo = getUserInfo();
        String merchantInfo = getMerchantInfo();*/

        // 使用方法引用替代Callable中call()方法的实现
        Callable<String> task = CallableTest::getGoodsInfo;
        FutureTask<String> futureTask = new FutureTask<>(task);
        Callable<String> task2 = CallableTest::getUserInfo;
        FutureTask<String> futureTask2 = new FutureTask<>(task2);
        Callable<String> task3 = CallableTest::getMerchantInfo;
        FutureTask<String> futureTask3 = new FutureTask<>(task3);

        // 创建线程对象，并启动多线程
        Thread thread = new Thread(futureTask);
        Thread thread2 = new Thread(futureTask2);
        Thread thread3 = new Thread(futureTask3);
        thread.start();
        thread2.start();
        thread3.start();

        // 等待获取各任务的返回值
        String goodsInfo = futureTask.get();
        String userInfo = futureTask2.get();
        String merchantInfo = futureTask3.get();

        long end = System.currentTimeMillis();
        System.out.println("共计耗时:" + (end - start));
    }

    // 获取商品消息，根据商品id获取
    private static String getGoodsInfo() throws InterruptedException {
        Thread.sleep(3000);
        return "商品信息";
    }

    private static String getUserInfo() throws InterruptedException {
        Thread.sleep(1000);
        return "用户信息";
    }

    private static String getMerchantInfo() throws InterruptedException {
        Thread.sleep(2000);
        return "商家信息";
    }


    private static void test() throws ExecutionException, InterruptedException {
        // Callable接口中的call方法，能够实现发布具有返回值的任务
        Callable<String> call = () -> {
            System.out.println("这是一个call方法");
            Thread.sleep(10000);
            System.out.println("休眠过后的代码");
            return "hello";
        };
        // 创建一个叫做FutureTask类的对象，在创建时可以将call对象放入
        FutureTask<String> task = new FutureTask<>(call);
        // 在创建线程对象时，可以指定传入FutureTask类的对象
        Thread t = new Thread(task);
        t.start();
        // 期望得到t线程执行后的结果，等待t线程执行完毕之后执行main方法中的内容
        // 可以调用FutureTask类中的get()方法，其会等待任务线程执行完毕后，将任务的返回值进行返回
        // 任务没有执行完毕前，执行本行代码的线程会一直处于阻塞状态
        String unused = task.get();
        System.out.println(unused);

        System.out.println("这是main线程的内容");
    }
}
